# Copyright (c) 2020 Presto Labs Pte. Ltd.
# Author: jingyuan

from ..on_log import OnLog
from .base import ExportDataFrame


class FillAfterConfirm(ExportDataFrame, OnLog):
  def __init__(self, confirm_to_fill_limit_sec=0):
    super().__init__()
    self.tolerance = confirm_to_fill_limit_sec
    self.cancel_ts = {}
    self.confirm_ts = {}
    self.errors = {}
    self.ts_fields = ['cancel_ts', 'cancel_confirm_ts', 'last_fill_ts']

  def on_cancel_submit(self, ts, symbol, order_id):
    self.cancel_ts[order_id] = ts

  def on_cancel_confirm(self, ts, currency, order_id):
    self.confirm_ts[order_id] = ts

  def on_fill(self, ts, currency, order_id, order_side, fill_price, fill_qty, maker):
    if order_id in self.confirm_ts and (ts - self.confirm_ts[order_id]) / 1e9 > self.tolerance:
      cancel_ts = self.cancel_ts.get(order_id, 0)
      confirm_ts = self.confirm_ts.get(order_id, 0)
      self.errors[order_id] = {
          'order_id': order_id,
          'cancel_ts': cancel_ts,
          'cancel_confirm_ts': confirm_ts,
          'confirm_duration(sec)': (confirm_ts - cancel_ts) / 1e9,
          'cancel_confirm_to_fill(sec)': (ts - confirm_ts) / 1e9,
          'last_fill_ts': ts,
          'side': order_side,
          'price': fill_price,
          'qty': fill_qty,
      }

  def to_df(self):
    return super().to_df().sort_values('cancel_confirm_to_fill(sec)', ascending=False)
